<template>
  <div class="edit">
    <div class="info">
      基本信息
    </div>
    <div class="basic">
      <nut-form>
        <nut-form-item label="logo">
          <nut-uploader :url="uploadUrl" accept="image/*" maximum="1" multiple v-model:file-list="logoFileList"
            @success="logoSucc">
          </nut-uploader>
        </nut-form-item>
        <nut-form-item label="店铺图片">
          <nut-uploader :url="uploadUrl" accept="image/*" @success="picSucc" v-model:file-list="picFileList" maximum="1"
            multiple>
          </nut-uploader>
        </nut-form-item>
        <nut-form-item label="店铺名称">
          <nut-input v-model="basicData.storeName" class="nut-input-text" placeholder="请输入店铺名称" type="text" />
        </nut-form-item>
        <nut-form-item label="店铺法人">
          <nut-input v-model="basicData.storeLepName" class="nut-input-text" placeholder="请输入店铺法人" type="text" />
        </nut-form-item>
        <nut-form-item label="联系方式">
          <nut-input v-model="basicData.storeLepPhone" class="nut-input-text" placeholder="请输入联系方式" type="text" />
        </nut-form-item>
        <nut-form-item label="地址">
          <view @click="visible = true">{{ basicData.place || '请选择地址' }}</view>
        </nut-form-item>
        <nut-form-item label="详细地址">
          <nut-textarea v-model="basicData.initPlace" limit-show max-length="200"
            placeholder="请输入店铺详细地址,例如xxx街道xxx广场xxx号" />
        </nut-form-item>
        <nut-form-item label="店铺简介">
          <nut-textarea v-model="basicData.storeRemark" limit-show max-length="200" placeholder="请输入店铺简介" />
        </nut-form-item>
        <nut-form-item label="店铺二维码">
          <img :src="qrcode" alt="" @click="saveImg">
        </nut-form-item>
      </nut-form>
      <div class="list">
        <div class="title">
          <nut-row :gutter="3">
            <nut-col :span="4">子账号
            </nut-col>
            <nut-col :span="5">
              <div class="itemAdd">
                <Plus color="#3A9AD3" size="14" @click="addSub" />添加
              </div>
            </nut-col>
          </nut-row>
        </div>
        <div class="item" v-for="item in list" :key="item.phonenumber">
          {{ item.phonenumber }}
          <MaskClose color="#FA2C19" size="14" @click="del(item.phonenumber)" />
        </div>
        <!-- <nut-button block type="info" class="subBtn" @click="addSub">新增子账号</nut-button> -->
      </div>
    </div>
    <nut-popup v-model:visible="show" :style="{ padding: '30px 50px', width: '80%' }">
      <nut-searchbar v-model="keyword" placeholder="请输入手机号查询" @search="search">
        <template #rightin>
          <Search2 />
        </template>
      </nut-searchbar>
      <div class="search-box">
        <span class="result" v-if="result.phonenumber">{{ result.phonenumber }}</span>
        <nut-empty description="未查询到搜索结果" v-else></nut-empty>
      </div>
      <div class="btns flex-a flex-b">
        <nut-button type="default" size="small" @click="cancle">取消</nut-button>
        <nut-button type="info" size="small" @click="addAccount">绑定</nut-button>
      </div>
    </nut-popup>
    <div class="btn flex-a">
      <nut-button block type="info" @click="submit">提交</nut-button>
    </div>
    <nut-cascader v-model:visible="visible" v-model="address" title="选择地址" :options="options" text-key="name"
      value-key="name" children-key="childList" @change="change"></nut-cascader>
  </div>
</template>

<script>
import Taro, { useRouter } from '@tarojs/taro';
import { reactive, toRefs, onMounted, ref } from 'vue';
import { addStore, getStoreInfo, editStore, getCity, bindUnBind, searchPhone, phoneList, getQrcode } from '../../../api/index'
import { RectRight, Search2, MaskClose, Plus } from '@nutui/icons-vue-taro';
import { uploadUrl } from '../../../utils/index.js'
export default {
  name: 'addStore',
  components: {
    RectRight,
    Search2,
    MaskClose,
    Plus,
  },
  setup() {
    const state = reactive({
      uploadUrl: uploadUrl,
      basicData: {
        place: ''
      },
      openId: '',
      logoFileList: [],
      picFileList: [],
      visible: false,
      options: [],
      show: false,
      keyword: '',
      openId: '',
      list: [],
      result: {},
      qrcode: '',
    });
    onMounted(() => {
      Taro.getStorage({
        key: 'user',
        success: function (res) {
          if (res.data.openId) {
            state.openId = res.data.openId
            getPhoneList(res.data.openId)
          }
        }
      })
      getCity().then(res => {
        if (res.code == 200) {
          state.options = res.data
        }
      })
      const router = useRouter();
      if (router.params.openId) {
        state.openId = router.params.openId
        if (router.params.openId) {
          Taro.setNavigationBarTitle({
            title: '编辑店铺'
          })
          getStoreInfo(router.params.openId).then(res => {
            if (res.code == 200) {
              state.basicData = res.data
              state.logoFileList.push(
                {
                  name: '',
                  url: res.data.storeLogo,
                  status: 'success',
                  message: '上传成功',
                  type: 'image',
                }
              )
              state.picFileList.push(
                {
                  name: '',
                  url: res.data.storePic,
                  status: 'success',
                  message: '上传成功',
                  type: 'image',
                }
              )
              getQrcode({
                storeNo: res.data.storeNo,
                storeName: res.data.storeName,
                storeRemark: res.data.storeRemark,
                storeLogo: res.data.storeLogo
              }).then(res => {
                state.qrcode = res
              })
            }
          })
        } else {
          Taro.setNavigationBarTitle({
            title: '新增店铺'
          })
        }
      }
    });
    const logoSucc = (data, option, fileItem) => {
      console.log(JSON.parse(data.data.data).url)
      state.basicData.storeLogo = JSON.parse(data.data.data).url
    }
    const picSucc = (data, option, fileItem) => {
      state.basicData.storePic = JSON.parse(data.data.data).url
    }
    const submit = () => {
      // state.basicData.storeLogo = state.basicData.storeLogo[0].url
      // state.basicData.storePic = state.basicData.storePic[0].url
      if (state.openId) {
        editStore(state.basicData).then(res => {
          if (res.code == 200) {
            Taro.showToast({
              title: '编辑成功',
              icon: 'success',
              duration: 2000
            })
            Taro.navigateTo({
              url: '/pages/cartpage/index'
            })
          }
        })
      } else {
        addStore(state.basicData).then(res => {
          if (res.code == 200) {
            Taro.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 2000
            })
            Taro.navigateTo({
              url: '/pages/cartpage/index'
            })
          }
        })
      }
    }
    const change = (args) => {
      console.log('change', args.toString());
      state.basicData.place = args.toString()
    };
    const addSub = () => {
      state.show = true
      state.keyword = ''
      state.result = {}
    }
    const search = () => {
      searchPhone(state.keyword).then(res => {
        if (res.code == 200) {
          state.result = res.data
        }
      })
    }
    const del = (phone) => {
      bindOrUnbind(state.openId, phone)
    }
    const bindOrUnbind = (openId, phonenumber) => {
      bindUnBind(openId, phonenumber).then(res => {
        if (res.code == 200) {
          Taro.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 2000
          })
          state.show = false
          state.keyword = ''
          state.result = {}
          getPhoneList(state.openId)
        } else {
          Taro.showToast({
            title: res.msg,
            icon: 'error',
            duration: 2000
          })
        }
      })
    }
    const addAccount = () => {
      if (state.result.phonenumber) {
        bindOrUnbind(state.openId, state.result.phonenumber)
      } else {
        Taro.showToast({
          title: '请先查询结果',
          icon: 'error',
          duration: 2000
        })
      }
    }
    const cancle = () => {
      state.show = false
      state.keyword = ''
      state.result = {}
    }
    const getPhoneList = (openId) => {
      phoneList(openId).then(res => {
        if (res.code == 200) {
          state.list = res.data
        }
      })
    }
    const saveImg = () => {
      Taro.getImageInfo({
        src: state.qrcode,
        success: function (res) {
          Taro.saveImageToPhotosAlbum({
            filePath: res.path,
            success: function (res) {
              Taro.showToast({
                title: '保存成功',
                icon: 'ersuccessror',
                duration: 2000
              })
            }
          })
        }
      })

    }
    return {
      ...toRefs(state), logoSucc, picSucc, submit, change, addSub, search, cancle, del, addAccount, getPhoneList, bindOrUnbind, saveImg
    }
  }
}
</script>
<style lang="scss">
.edit {
  background: #F0F0F0;
  min-height: 100vh;

  .info {
    padding: 20rpx 20rpx 10rpx;
    color: #747474;
    font-size: 26rpx;
  }

  .spec {
    .stock {
      white-space: nowrap;

      text {
        margin-left: 20rpx;
        color: #3A9AD3;
      }
    }
  }

  .add {
    padding: 20rpx;
    background: #fff;
    color: #1994DF;
    font-size: 32rpx;

    text {
      display: inline-block;
      width: 35rpx;
      height: 35rpx;
      text-align: center;
      line-height: 30rpx;
      border-radius: 50%;
      font-weight: bold;
      border: 4rpx solid #1994DF;
      margin-right: 10rpx;
    }
  }

  .btn {
    text-align: center;
    background: #fff;
    padding: 20rpx;
    width: 100%;
    margin: 20rpx 0;
    justify-content: center;
    box-sizing: border-box;
  }

  .list {
    background: #fff;
    padding: 20rpx;

    .title {
      margin-bottom: 20rpx;
    }

    .item {
      display: inline-block;
      padding: 8rpx 12rpx;
      border: 1rpx solid #ccc;
      border-radius: 12rpx;
      font-size: 24rpx;
      margin-right: 20rpx;
      margin-bottom: 10rpx;
    }

    .itemAdd {
      display: inline-flex;
      align-items: center;
      padding: 8rpx 8rpx;
      border: 1rpx solid #ccc;
      border-radius: 12rpx;
      font-size: 20rpx;
      margin-right: 20rpx;
      margin-bottom: 10rpx;
    }

    .subBtn {
      width: 100%;
      margin: 20rpx 0 0;
      box-sizing: border-box;
    }
  }

  .nut-popup {
    padding: 0 !important;

    .btns {
      padding: 0 180rpx 20rpx;
    }

    .search-box {
      height: 120rpx;
      overflow-y: auto;
      padding: 20rpx 40rpx;
      box-sizing: border-box;

      .result {
        display: inline-block;
        padding: 8rpx 12rpx;
        border: 1rpx solid #ccc;
        border-radius: 12rpx;
        font-size: 24rpx;
      }
    }
  }
}
</style>
